/**
 * Copyright (C), 2015-2024, XXX有限公司
 * FileName: MyDoubleLinkList
 * Author:   Administrator
 * Date:     2024/3/24 17:01
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author Administrator
 * @create 2024/3/24
 * @since 1.0.0
 */
public class MyDoubleLinkList<T> {

    Node<T> first;


    Node<T> last;

    int size;


    public MyDoubleLinkList() {
        this.first = null;
        this.last = null;
        this.size = 0;
    }

    public int size() {
        return size;
    }

    public void add(T t) {
        //将last存储在prev节点
        Node<T> prev = last;
        // 创建需要插入的节点
        Node<T> node = new Node<T>(prev, t, null);
        if (prev == null) {
            //如果prev为空，说明是第一个节点
            first = node;
        } else {
            prev.next = node;
        }
        //将last指向新节点
        last = node;
        this.size++;
    }

    private Node<T> getNode(int pos) {
        if (first == null) {
            return null;
        }
        int middle = this.size / 2;
        if (pos < middle) {
            //从开始遍历
            Node<T> x = first;
            for (int i = 0; i < pos; i++) {
                x = x.next;
            }
            return x;
        } else {
            //从尾部遍历
            Node<T> x = last;
            for (int i = size - 1; i > pos; i--) {
                x = x.prev;
            }
            return x;
        }
    }

    public T get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        return getNode(index).item;
    }

    private class Node<T> {

        T item;

        Node<T> prev;

        Node<T> next;

        public Node(Node<T> prev, T item, Node<T> next) {
            this.item = item;
            this.prev = prev;
            this.next = next;
        }
    }
}